// 导入依赖
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 设置基础 URL
const baseURL = '/api'

// 创建 Axios 实例
const instance = axios.create({ baseURL })

// 不需要携带 token 的接口路径（白名单）
const noTokenUrls = ['/user/login', '/user/getcode']

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    
    // 判断是否是白名单接口
    const skipToken = noTokenUrls.some((url) => config.url.includes(url))
    
    // 如果不是白名单接口并且有 token，就加上
    if (token && !skipToken) {
      config.headers.Authorization = 'Bearer ' + token
    }
    // console.log(config.headers.Authorization);
    
    
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    //  console.log(response,"   response");
    
    const { data, config } = response
    // 如果是验证码接口，直接返回
    if (config.url.includes('/getcode')) {
      return data
    }


    // 正常业务处理
    if (response.status === 200) {
      return data
    } else {
      ElMessage.error(data.message || '服务异常')
      return Promise.reject(data)
    }
  },
  (error) => {
    console.log(error);
    
    // // 如果是 401，则跳转登录页
    // if (error.response.status === 401) {
    //   ElMessage.error('请先登录')
    //   router.replace('/login')
    // } else {
    //   ElMessage.error('请求出错，请稍后再试')
    // }
    return Promise.reject(error)
  }
)


// 包装统一的请求函数
const request = ({ url, method = 'GET', data = {}, headers = {} }) => {
  const upperMethod = method.toUpperCase()

  return instance({
    url,
    method: upperMethod,
    headers,
    ...(upperMethod === 'GET' ? { params: data } : { data })
  })
}

// 扩展快捷方法：request.get / request.post 等
request.get = (url, params = {}, headers = {}) =>
  request({ url, method: 'GET', data:params, headers })

request.post = (url, data = {}, headers = {}) =>
  request({ url, method: 'POST', data, headers })

request.put = (url, data = {}, headers = {}) =>
  request({ url, method: 'PUT', data, headers })

request.delete = (url, data = {}, headers = {}) =>
  request({ url, method: 'DELETE', data, headers })

export default request
